package com.wsoft.excel.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 用于 Excel 导入 LocalDateTime 类型转换
 * @Author z001
 * @Date 2024/11/6 16:04
 */
public class LocalDateTimeConverter implements Converter<LocalDateTime> {


    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public Class supportJavaTypeKey() {
        return LocalDateTime.class;
    }

    @Override
    public WriteCellData<String> convertToExcelData(WriteConverterContext<LocalDateTime> context) throws Exception {
        if (context.getValue() == null) {
            return new WriteCellData("");
        }
        return new WriteCellData(context.getValue().format(DATE_TIME_FORMATTER));
    }

    @Override
    public LocalDateTime convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        try {
            String value = cellData.getStringValue();
            if (value == null || value.isEmpty()) {
                return null;
            }
            return LocalDateTime.parse(value, DATE_TIME_FORMATTER);
        } catch (Exception e) {
            throw new RuntimeException("Failed to convert cell data to LocalDateTime", e);
        }
    }
}
